#include "src/intersect_error/lines_error.h"

void GenerateTest() {

    int num_tests = 1000000;
    std::vector<double> results;
    Point intersection{};
    double max_error = -1.0;
    double min = -1.0, max = 1.0;
    double sum_error = 0.0;

    double num{};

    for (int i = 0; i < num_tests; i++) {
        double error{};

        Point p1(RandomDouble(min, max), RandomDouble(min, max));
        Point p2(RandomDouble(min, max), RandomDouble(min, max));

        Point mid = Midpoint(p1,p2);

        Point p3(RandomDouble(min, max), RandomDouble(min, max));

        Point p4 = ReflectPoint(p3,mid);


        LineSegment line1(p1, p2);
        LineSegment line2(p3, p4);

        std::cout << std::fixed << std::setprecision(2);

        //std::cout << "\nTest " << i + 1 << ": \n";
        //std::cout << "Line 1 : (" << p1.x << ", " << p1.y << ") to (" << p2.x << ", " << p2.y << ")\n";
        //std::cout << "Line 2 : (" << p3.x << ", " << p3.y << ") to (" << p4.x << ", " << p4.y << ")\n";

        if(line1.Intersects(line2,intersection)){

            std::cout << std::fixed << std::setprecision(4);

            //std::cout << "The lines intersect at (" << intersection.x << "," << intersection.y << ")" << std::endl;
            //std::cout << "actual point(" << mid.x << "," << mid.y << ")" << std::endl;

            if(std::isnan(intersection.x) || std::isnan(intersection.y)){

                std::cout << "Lines are parallel or collinear,no valid intersection point.\n";
                continue;
            }

            error = Distance(intersection,mid);

            if(error > 1e-12) num++;

            if(!std::isnan(error)){

                results.push_back((error));

                sum_error += error;

                //std::cout << "current error " << std::scientific << error << std::endl;

                if(error > max_error){

                    max_error = error;
                    //std::cout << "updated maxerror to " << std::scientific << max_error << std::endl;
                }



            }else{

                //std::cout << "Encountered NaN error,skipping this test case." << std::endl;
            }



        }else{

            //std::cout << "\nThe lines do not intersection.\n" << std::endl;

        }


}
    std::cout << std::endl;

    std::cout << "\nMax error: " << std::scientific << max_error << "\n";
    std::cout << "\nAvgrage Error: " << sum_error / results.size() << std::endl;
    std::cout << std::fixed << std::setprecision(2) <<"\nThe probability of error exceeding 1e-12:" << num / results.size() * 100 << "%" << std::endl;
}

int main()
{

    GenerateTest();


    return 0;
}
